#!/usr/bin/env python3
"""
小红书功能初始化脚本
用于创建数据库表和初始化配置
"""

import os
import sys
import sqlite3
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from app.core.config import settings
from app.db.session import engine
from app.models.xiaohongshu import XiaohongshuAccount, XiaohongshuPublishLog, XiaohongshuToken
from sqlalchemy import text
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def create_tables():
    """创建小红书相关的数据库表"""
    try:
        logger.info("开始创建小红书相关数据库表...")
        
        # 读取SQL文件
        sql_file = project_root / "migrations" / "add_xiaohongshu_tables.sql"
        
        if not sql_file.exists():
            logger.error(f"SQL文件不存在: {sql_file}")
            return False
        
        with open(sql_file, 'r', encoding='utf-8') as f:
            sql_content = f.read()
        
        # 分割SQL语句
        sql_statements = [stmt.strip() for stmt in sql_content.split(';') if stmt.strip()]
        
        # 执行SQL语句
        with engine.connect() as conn:
            for sql in sql_statements:
                if sql.strip():
                    try:
                        conn.execute(text(sql))
                        logger.info(f"执行SQL成功: {sql[:50]}...")
                    except Exception as e:
                        logger.warning(f"执行SQL失败: {e}, SQL: {sql[:50]}...")
            
            conn.commit()
        
        logger.info("小红书数据库表创建完成")
        return True
        
    except Exception as e:
        logger.error(f"创建数据库表失败: {e}")
        return False


def init_browser_data_dir():
    """初始化浏览器数据目录"""
    try:
        # 创建浏览器数据目录
        user_data_dir = settings.XIAOHONGSHU_USER_DATA_DIR or os.path.join(
            os.path.expanduser("~"), ".cool-red-browser-data"
        )
        
        os.makedirs(user_data_dir, exist_ok=True)
        logger.info(f"浏览器数据目录已创建: {user_data_dir}")
        
        return True
        
    except Exception as e:
        logger.error(f"初始化浏览器数据目录失败: {e}")
        return False


def install_playwright():
    """安装Playwright浏览器"""
    try:
        logger.info("开始安装Playwright浏览器...")
        
        import subprocess
        
        # 安装Playwright浏览器
        result = subprocess.run(
            [sys.executable, "-m", "playwright", "install", "chromium"],
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0:
            logger.info("Playwright浏览器安装成功")
            return True
        else:
            logger.error(f"Playwright浏览器安装失败: {result.stderr}")
            return False
            
    except Exception as e:
        logger.error(f"安装Playwright浏览器失败: {e}")
        return False


def check_dependencies():
    """检查依赖项"""
    try:
        logger.info("检查依赖项...")
        
        # 检查playwright
        try:
            import playwright
            try:
                from playwright import __version__
                logger.info(f"Playwright版本: {__version__}")
            except ImportError:
                logger.info("Playwright已安装")
        except ImportError:
            logger.error("Playwright未安装，请运行: pip install playwright")
            return False
        
        # 检查其他依赖
        dependencies = [
            'fastapi',
            'sqlalchemy',
            'pydantic',
            'requests'
        ]
        
        for dep in dependencies:
            try:
                __import__(dep)
                logger.info(f"✓ {dep} 已安装")
            except ImportError:
                logger.error(f"✗ {dep} 未安装")
                return False
        
        logger.info("所有依赖项检查通过")
        return True
        
    except Exception as e:
        logger.error(f"检查依赖项失败: {e}")
        return False


def create_env_example():
    """创建环境变量示例文件"""
    try:
        env_example_content = """
# 小红书配置示例
# 复制此文件为 .env 并填入实际值

# 小红书浏览器配置
XIAOHONGSHU_HEADLESS=true
XIAOHONGSHU_TIMEOUT=30000
XIAOHONGSHU_USER_DATA_DIR=
XIAOHONGSHU_AUTO_LOGIN=false
XIAOHONGSHU_LOGIN_CHECK_INTERVAL=3600
XIAOHONGSHU_ACCOUNT_SYNC_INTERVAL=7200

# 数据库配置
DATABASE_URL=sqlite:///./xiaohongshu.db

# 对象存储配置
STORAGE_PROVIDER=minio
S3_ENDPOINT=http://localhost:9000
S3_ACCESS_KEY=minioadmin
S3_SECRET_KEY=minioadmin
S3_BUCKET=xiaohongshu-posts
S3_REGION=us-east-1

# XXL-Job配置
XXL_JOB_ADMIN_URL=http://localhost:8080/xxl-job-admin
XXL_JOB_USERNAME=admin
XXL_JOB_PASSWORD=123456
XXL_JOB_EXECUTOR_APP_NAME=xiaohongshu-executor
XXL_JOB_EXECUTOR_PORT=9999
XXL_JOB_EXECUTOR_HOST=localhost
XXL_JOB_ACCESS_TOKEN=default_token
XXL_JOB_AUTO_REGISTRY=true

# 安全配置
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# AI服务配置
LLM_PROVIDER=openai
OPENAI_API_KEY=
OPENAI_BASE_URL=

# Playwright配置
PLAYWRIGHT_HEADLESS=true
PLAYWRIGHT_TIMEOUT=30000
"""
        
        env_example_file = project_root / ".env.xiaohongshu.example"
        
        with open(env_example_file, 'w', encoding='utf-8') as f:
            f.write(env_example_content.strip())
        
        logger.info(f"环境变量示例文件已创建: {env_example_file}")
        return True
        
    except Exception as e:
        logger.error(f"创建环境变量示例文件失败: {e}")
        return False


def main():
    """主函数"""
    logger.info("开始初始化小红书功能...")
    
    success = True
    
    # 1. 检查依赖项
    if not check_dependencies():
        success = False
    
    # 2. 创建数据库表
    if not create_tables():
        success = False
    
    # 3. 初始化浏览器数据目录
    if not init_browser_data_dir():
        success = False
    
    # 4. 安装Playwright浏览器
    if not install_playwright():
        logger.warning("Playwright浏览器安装失败，请手动运行: python -m playwright install chromium")
    
    # 5. 创建环境变量示例文件
    if not create_env_example():
        success = False
    
    if success:
        logger.info("\n" + "="*50)
        logger.info("小红书功能初始化完成！")
        logger.info("="*50)
        logger.info("下一步操作:")
        logger.info("1. 复制 .env.xiaohongshu.example 为 .env 并填入实际配置")
        logger.info("2. 启动应用: python start.py --dev")
        logger.info("3. 访问 http://localhost:8000/docs 查看API文档")
        logger.info("4. 使用 /api/v1/xiaohongshu/login/open 打开登录页面")
        logger.info("5. 手动登录后使用 /api/v1/xiaohongshu/login/save 保存登录信息")
        logger.info("="*50)
    else:
        logger.error("小红书功能初始化失败，请检查错误信息")
        sys.exit(1)


if __name__ == "__main__":
    main()